#include "Commands.h"
#include "UserInterface.h"
#include "Assert.h"

Command Commands::parse(const string & commandName) {
	static Commands commands;
	string commandNameInUppercase(convertToUppercase(commandName));
	Command command = commands[commandNameInUppercase];
	return command;
}

Commands::Commands() {
	this->commands["L"] = COMMAND_MOVE_LEFT;
	this->commands["R"] = COMMAND_MOVE_RIGHT;
	this->commands["U"] = COMMAND_MOVE_UP;
	this->commands["D"] = COMMAND_MOVE_DOWN;
	this->commands["TOP"] = COMMAND_TOP;
	this->commands["RESTART"] = COMMAND_RESTART;
	this->commands["EXIT"] = COMMAND_EXIT;
}

Command Commands::operator [](const string &commandName) {
	Command command(COMMAND_INVALID_COMMAND);
	map<string, Command>::const_iterator commandPosition = this->commands.find(commandName);
	if (commandPosition != this->commands.end()) {
		command = commandPosition->second;
	}
	ASSERT(command == COMMAND_INVALID_COMMAND ||
		command == COMMAND_MOVE_LEFT ||
		command == COMMAND_MOVE_RIGHT ||
		command == COMMAND_MOVE_UP ||
		command == COMMAND_MOVE_DOWN ||
		command == COMMAND_TOP ||
		command == COMMAND_RESTART ||
		command == COMMAND_EXIT);
	return command;
}

string Commands::convertToUppercase(const string &name) {
	locale loc;
	string uppercaseName(name.size(), '\0');
	for (unsigned int i = 0; i < name.size(); i++) {
		uppercaseName[i] = toupper(name[i], loc);
	}
	return uppercaseName;
}
